// AI智能童话书前端脚本

class FairyTaleApp {
    constructor() {
        this.currentStep = 'profile';
        this.userProfile = {};
        this.storyData = {};
        this.init();
    }

    init() {
        this.bindEvents();
        this.loadStoryTemplates();
    }

    bindEvents() {
        // 绑定表单提交事件
        document.addEventListener('submit', (e) => {
            if (e.target.id === 'profileForm') {
                e.preventDefault();
                this.handleProfileSubmit();
            } else if (e.target.id === 'templateForm') {
                e.preventDefault();
                this.handleTemplateSubmit();
            }
        });

        // 绑定选择事件
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('template-card')) {
                this.selectTemplate(e.target);
            } else if (e.target.classList.contains('choice-button')) {
                this.makeChoice(e.target.dataset.choice);
            }
        });
    }

    async loadStoryTemplates() {
        try {
            const response = await fetch('/api/templates');
            const templates = await response.json();
            this.renderTemplates(templates);
        } catch (error) {
            console.error('加载故事模板失败:', error);
            this.showAlert('加载故事模板失败，请刷新页面重试', 'danger');
        }
    }

    renderTemplates(templates) {
        const container = document.getElementById('storyTemplates');
        if (!container) return;

        container.innerHTML = Object.values(templates).map(template => `
            <div class="template-card" data-template="${template.id}">
                <span class="template-icon">${template.icon}</span>
                <div class="template-name">${template.name}</div>
                <div class="template-description">${template.description}</div>
                <div class="template-age">适合年龄: ${template.suitable_age}</div>
            </div>
        `).join('');
    }

    selectTemplate(element) {
        // 移除其他选中状态
        document.querySelectorAll('.template-card').forEach(card => {
            card.classList.remove('selected');
        });
        
        // 添加选中状态
        element.classList.add('selected');
        
        // 保存选择
        this.userProfile.selectedTemplate = element.dataset.template;
        
        // 启用开始按钮
        const startButton = document.getElementById('startStoryBtn');
        if (startButton) {
            startButton.disabled = false;
            startButton.classList.add('btn-primary');
            startButton.classList.remove('btn-secondary');
        }
    }

    async handleProfileSubmit() {
        const form = document.getElementById('profileForm');
        const formData = new FormData(form);
        
        this.userProfile = {
            name: formData.get('name'),
            age: formData.get('age'),
            interests: formData.getAll('interests'),
            difficulty: formData.get('difficulty')
        };

        // 验证表单
        if (!this.userProfile.name || !this.userProfile.age) {
            this.showAlert('请填写完整的个人信息', 'warning');
            return;
        }

        // 显示模板选择
        this.showStep('template');
    }

    async handleTemplateSubmit() {
        if (!this.userProfile.selectedTemplate) {
            this.showAlert('请选择一个故事类型', 'warning');
            return;
        }

        this.showLoading('正在生成您的专属童话故事...');

        try {
            const response = await fetch('/api/start_story', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify(this.userProfile)
            });

            const result = await response.json();
            
            if (result.success) {
                this.storyData = result.story;
                this.showStory();
            } else {
                throw new Error(result.error || '生成故事失败');
            }
        } catch (error) {
            console.error('生成故事失败:', error);
            this.showAlert('生成故事失败，请重试', 'danger');
        } finally {
            this.hideLoading();
        }
    }

    async makeChoice(choiceIndex) {
        this.showLoading('正在生成下一章节...');

        try {
            const response = await fetch('/api/make_choice', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    story_id: this.storyData.id,
                    choice_index: parseInt(choiceIndex)
                })
            });

            const result = await response.json();
            
            if (result.success) {
                this.storyData = result.story;
                this.updateStory();
            } else {
                throw new Error(result.error || '选择失败');
            }
        } catch (error) {
            console.error('处理选择失败:', error);
            this.showAlert('处理选择失败，请重试', 'danger');
        } finally {
            this.hideLoading();
        }
    }

    showStep(step) {
        // 隐藏所有步骤
        document.querySelectorAll('.step').forEach(el => {
            el.style.display = 'none';
        });

        // 显示目标步骤
        const targetStep = document.getElementById(`${step}Step`);
        if (targetStep) {
            targetStep.style.display = 'block';
            targetStep.classList.add('fade-in');
        }

        this.currentStep = step;
    }

    showStory() {
        this.showStep('story');
        this.updateStory();
        this.updateProgress();
    }

    updateStory() {
        const storyText = document.getElementById('storyText');
        const storyChoices = document.getElementById('storyChoices');
        
        if (storyText) {
            storyText.innerHTML = this.storyData.current_text;
            storyText.classList.add('fade-in');
        }

        if (storyChoices && this.storyData.choices) {
            storyChoices.innerHTML = this.storyData.choices.map((choice, index) => `
                <button class="choice-button slide-in" data-choice="${index}">
                    ${choice}
                </button>
            `).join('');
        }

        this.updateProgress();
    }

    updateProgress() {
        const progressFill = document.getElementById('progressFill');
        const progressText = document.getElementById('progressText');
        
        if (progressFill && this.storyData.progress !== undefined) {
            const progress = Math.round(this.storyData.progress * 100);
            progressFill.style.width = `${progress}%`;
            
            if (progressText) {
                progressText.textContent = `故事进度: ${progress}%`;
            }
        }
    }

    showLoading(message = '加载中...') {
        const loadingEl = document.getElementById('loading');
        const loadingMessage = document.getElementById('loadingMessage');
        
        if (loadingEl) {
            loadingEl.style.display = 'flex';
            if (loadingMessage) {
                loadingMessage.textContent = message;
            }
        }
    }

    hideLoading() {
        const loadingEl = document.getElementById('loading');
        if (loadingEl) {
            loadingEl.style.display = 'none';
        }
    }

    showAlert(message, type = 'info') {
        // 移除现有的alert
        const existingAlert = document.querySelector('.alert');
        if (existingAlert) {
            existingAlert.remove();
        }

        // 创建新的alert
        const alert = document.createElement('div');
        alert.className = `alert alert-${type} fade-in`;
        alert.textContent = message;

        // 插入到页面顶部
        const container = document.querySelector('.container');
        if (container) {
            container.insertBefore(alert, container.firstChild);
        }

        // 3秒后自动移除
        setTimeout(() => {
            if (alert.parentNode) {
                alert.remove();
            }
        }, 3000);
    }

    // 重新开始故事
    restartStory() {
        this.userProfile = {};
        this.storyData = {};
        this.showStep('profile');
        
        // 重置表单
        const forms = document.querySelectorAll('form');
        forms.forEach(form => form.reset());
        
        // 移除模板选择
        document.querySelectorAll('.template-card').forEach(card => {
            card.classList.remove('selected');
        });
    }

    // 保存故事进度
    async saveProgress() {
        try {
            const response = await fetch('/api/save_progress', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    story_id: this.storyData.id,
                    progress: this.storyData.progress
                })
            });

            const result = await response.json();
            if (result.success) {
                this.showAlert('进度已保存', 'success');
            }
        } catch (error) {
            console.error('保存进度失败:', error);
        }
    }

    // 获取学习报告
    async getLearningReport() {
        try {
            const response = await fetch('/api/learning_report', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    story_id: this.storyData.id
                })
            });

            const result = await response.json();
            if (result.success) {
                this.showLearningReport(result.report);
            }
        } catch (error) {
            console.error('获取学习报告失败:', error);
            this.showAlert('获取学习报告失败', 'danger');
        }
    }

    showLearningReport(report) {
        // 创建报告模态框
        const modal = document.createElement('div');
        modal.className = 'modal';
        modal.innerHTML = `
            <div class="modal-content">
                <h3>📊 学习报告</h3>
                <div class="report-content">
                    <p><strong>学习时长:</strong> ${report.duration}</p>
                    <p><strong>完成进度:</strong> ${report.progress}%</p>
                    <p><strong>掌握概念:</strong> ${report.concepts_learned}</p>
                    <p><strong>建议:</strong> ${report.recommendations}</p>
                </div>
                <button onclick="this.parentElement.parentElement.remove()" class="btn btn-primary">关闭</button>
            </div>
        `;
        
        document.body.appendChild(modal);
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.fairyTaleApp = new FairyTaleApp();
});

// 工具函数
function formatTime(seconds) {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = seconds % 60;
    return `${minutes}分${remainingSeconds}秒`;
}

function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}